#include "11-flymap_contrl.h"
#include <stdio.h>
#include <iostream>
#include <unistd.h>


extern "C"
{

}

FlyMapContrl *FlyMapContrl::_Instance = 0;
FlyMapContrl::FlyMapContrl() 
{
    
}


FlyMapContrl::~FlyMapContrl() 
{

}
void FlyMapContrl::initilize()
{   

}

bool FlyMapContrl::OtherThreadInit(void) 
{
    std::thread id(std::bind(&FlyMapContrl::OtherThread, this));
    m_otherId = std::move(id);
    //m_otherId.detach();

    return true;
}

int FlyMapContrl::OtherThread(void) {
    while (true) {
        printf("%s:%d %s\n", __FUNCTION__, __LINE__, "other thread running...");
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    return 0;
}

void FlyMapContrl::AlgoFinish()
{
	printf("==== %s:%d ====\n", __FUNCTION__, __LINE__);
    
    FinishThreadInit();
    FinishThreadUninit();
}

bool FlyMapContrl::FinishThreadInit(void) {

    m_bRunning = true;
    std::thread id(std::bind(&FlyMapContrl::SendThreadFinish, this));
    m_thId = std::move(id);
    //m_thId.detach();    /* 开启此行会报 terminate called after throwing an instance of 'std::system_error' */

    return true;
}

bool FlyMapContrl::FinishThreadUninit(void) {
    //m_bRunning = false;
    m_thId.join();      // 等待SendThreadFinish跳出

    return true;
}

int FlyMapContrl::SendThreadFinish(void) {
    int timeout = 0;

    while (m_bRunning) {
        printf("%s:%d %s\n", __FUNCTION__, __LINE__, "Waiting for photo transfer to complete...");
        std::this_thread::sleep_for(std::chrono::seconds(1));
        timeout++;

        if (timeout == 5) {
            break;
        }
    }

    return 0;
}

int main()
{
    FlyMapContrl obj;

    obj.OtherThreadInit();
    while (true) {
        obj.AlgoFinish();
        sleep(1);
    }

    return 0;
}
